package com.cloudfast.common.date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author liuyw
 * @描述:日期控制类
 * @date 2020年4月30日
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    private static final Logger logger = LoggerFactory.getLogger(Logger.class);

    public static final String DATEFORMAT = "yyyy-MM-dd";
    public static final String DATETIMEFORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String DATETIMEID = "yyyyMMddHHmmss";
    public static final String DATEID = "yyMMdd";
    public static final Pattern PATTEN_FORMAT = Pattern.compile("[A-Z]+");

    protected static final String[] DATEFORMATARRAY = {DATETIMEFORMAT, DATEFORMAT, "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss",
            "yyyyMMdd"};

    /**
     * 得到当前日期字符串 格式（yyyy-MM-dd） pattern可以为：DATEFORMAT "HH:mm:ss" "E"
     */
    public static String getDate(String pattern) {
        return DateFormatUtils.format(new Date(), pattern);
    }

    /**
     * @return
     * @descript:获取今天的日期 格式yyyy-MM-dd
     * @auth liuyw
     * @dateTime 2018年12月27日 上午10:23:25
     */
    public static String getDate() {
        return getDate(DATEFORMAT);
    }

    /**
     * 字符串转换日期
     *
     * @param str
     * @param formatPattern
     * @return
     */
    public static Date stringToDate(String str, String formatPattern) {
        if (hasChar(str)) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.UK);
            try {
                Date ss = dateFormat.parse(str);
                str = dateToString(ss, formatPattern);
            } catch (ParseException e) {
                logger.error(e.getMessage());
            }
        }

        SimpleDateFormat format = new SimpleDateFormat(formatPattern);
        if (StringUtils.isNotEmpty(str)) {
            try {
                return format.parse(str);
            } catch (ParseException e) {
                logger.error(e.getMessage());
            }
        }
        return null;
    }

    /**
     * 得到日期字符串 默认格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
     */
    public static String formatDate(Date date, Object... pattern) {
        String formatDate = null;
        if (pattern != null && pattern.length > 0) {
            formatDate = org.apache.commons.lang.time.DateFormatUtils.format(date, pattern[0].toString());
        } else {
            formatDate = org.apache.commons.lang.time.DateFormatUtils.format(date, "yyyy-MM-dd");
        }
        return formatDate;
    }

    /**
     * 得到当前时间字符串 格式（HH:mm:ss）
     */
    public static String getTime() {
        return formatDate(new Date(), "HH:mm:ss");
    }

    /**
     * 得到当前日期和时间字符串 格式（yyyy-MM-dd HH:mm:ss）
     */
    public static String getDateTime() {
        return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 得到当前年份字符串 格式（yyyy）
     */
    public static String getYear() {
        return formatDate(new Date(), "yyyy");
    }

    /**
     * 得到当前月份字符串 格式（MM）
     */
    public static String getMonth() {
        return formatDate(new Date(), "MM");
    }

    /**
     * 得到当天字符串 格式（dd）
     */
    public static String getDay() {
        return formatDate(new Date(), "dd");
    }
    /**
     * 获取昨天的日期
     * @param pattern
     * @return
     */
    public static String getYesterday(String pattern) {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_MONTH,-1);
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(c.getTime());
    }
    private static boolean hasChar(String fieldName) {
        boolean isChar = false;
        String[] fieldPattern = fieldName.split("");
        for (String s : fieldPattern) {
            Matcher m = PATTEN_FORMAT.matcher(s);
            if (m.matches()) {
                isChar = true;
            }
        }
        return isChar;
    }

    /**
     * 日期转换成字符串
     *
     * @param date
     * @return
     */
    public static String dateToString(Date date, String formatPattern) {
        SimpleDateFormat format = new SimpleDateFormat(formatPattern);
        return format.format(date);
    }

    /**
     * 加减小时:正数+;负数-
     *
     * @param hour
     * @param format
     * @return
     */
    public static String addHour(int hour, String format) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int _hour = calendar.get(Calendar.HOUR) + hour;
        calendar.set(Calendar.HOUR, _hour);// 让日期加1
        return new SimpleDateFormat(format).format(calendar.getTime());
    }

    /**
     * 加减日期
     *
     * @param timeType Calendar.HOUR ,Calendar.DAY,Calendar.MONTH
     * @param timeDiff
     * @param format
     * @return
     */
    public static String add(int timeType, int timeDiff, String format) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int _hour = calendar.get(timeType) + timeDiff;
        calendar.set(timeType, _hour);// 让日期加1
        return new SimpleDateFormat(format).format(calendar.getTime());
    }

    /**
     * 判的时间差(年,月,天)
     *
     * @param startDate
     * @param endDate
     * @return
     */
    @SuppressWarnings("deprecation")
    public static int diffDays(Date startDate, Date endDate) {
        LocalDate from = LocalDate.of(startDate.getYear(), startDate.getMonth(), startDate.getDay());
        LocalDate to = LocalDate.of(endDate.getYear(), endDate.getMonth(), endDate.getDay());
        long diffTime = to.toEpochDay() - from.toEpochDay();
        return Integer.parseInt(diffTime + "");
    }

    public static int diffHours(Date startDate, Date endDate) {
        long hourM = 1000 * 60 * 60;
        long differ = endDate.getTime() - startDate.getTime();
        long hour = differ / hourM;
        return Integer.parseInt(String.valueOf(hour));
    }
    /**
     * 周的开始和结束时间
     *
     * @param weekDay
     * @return
     */
    public static String weekDayStartAndEndDate(Date weekDay) {
        Calendar s = new GregorianCalendar();
        s.setFirstDayOfWeek(Calendar.MONDAY);
        s.setTime(weekDay);
        s.set(Calendar.DAY_OF_WEEK, s.getFirstDayOfWeek());
        Calendar e = new GregorianCalendar();
        e.setFirstDayOfWeek(Calendar.MONDAY);
        e.setTime(weekDay);
        e.set(Calendar.DAY_OF_WEEK, e.getFirstDayOfWeek() + 6);
        return dateToString(s.getTime(), "yyyy-MM-dd") + "~" + dateToString(e.getTime(), "yyyy-MM-dd");
    }

}